<!--
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2022-11-30 18:08:17
 * @LastEditors: Andy
 * @LastEditTime: 2023-03-28 14:47:06
-->
<template>
  <!-- <x-dialog
    :title="$t('system.user.jobSet')"
    :show.sync="isVisible"
    v-if="isVisible"
    :before-close="handleClose"
    width="80%"
  > -->
  <div>
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="flex-row justify-between">
          <span class="title">
            <!-- <em class="required-icon"> * </em> -->
            主岗：
          </span>
          <!-- <el-input placeholder="请输入内容" v-model="filterName" class="input-with-search">
            <el-button slot="append" icon="el-icon-search" @click="searchPost('main')" class="search-btn"></el-button>
          </el-input> -->
        </div>
        <tree-transfer
          :title="[$t('system.user.jobList'), $t('system.user.checkMainPost')]"
          :from_data="mainPostOptions"
          :to_data="checkedMainPost"
          v-if="isVisible"
          ref="mainPost"
          :defaultProps="defaultProps"
          @add-btn="transferMainAdd"
          @left-check-change="leftCheckChange"
          @remove-btn="remove"
          :mode="mode"
          height="436px"
          :key="'mainPost'"
          openAll
          :checkStrictly="true"
          :checkStrictlyType="'puppet'"
        >
        </tree-transfer>
      </el-col>
      <el-col :span="12">
        <div class="flex-row justify-between">
          <span class="title"> 副岗： </span>
          <!-- <el-input placeholder="请输入内容" v-model="filterJobName" class="input-with-search">
            <el-button slot="append" icon="el-icon-search" @click="searchPost('deputy')" class="search-btn"></el-button>
          </el-input> -->
        </div>
        <tree-transfer
          :title="[$t('system.user.jobList'), $t('system.user.checkDeputyPost')]"
          :from_data="subPostOptions"
          v-if="isVisible"
          :to_data="checkedSubPost"
          :key="'deputy'"
          ref="subPost"
          :defaultProps="defaultProps"
          @add-btn="transferDeputyAdd"
          @remove-btn="transferDeputyRemove"
          :mode="mode"
          height="436px"
          :checkStrictly="true"
          :checkStrictlyType="'puppet'"
          openAll
        >
        </tree-transfer>
      </el-col>
    </el-row>
    <!-- <span slot="footer">
      <el-button @click="handleClose"> {{ $t('common.cancel') }} </el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading"> {{ $t('common.confirm') }} </el-button>
    </span> -->
  </div>
</template>
<script>
  import treeTransfer from 'el-tree-transfer'
  import { clone, cloneDeep } from '@package/utils'
  import { apiPostTree } from '../../organization/api'
  import { apiPostUserPost } from '../api'
  import { EnumApiCode } from '../../../../../../globalEnum'

  export default {
    components: {
      treeTransfer
    },
    props: {
      userInfo: {
        type: Object,
        default: () => ({})
      }
    },
    data() {
      return {
        isVisible: false,
        loading: false,
        activeName: 'first',
        mainPostOptions: [],
        subPostOptions: [],
        parentId: 'parentId',
        checkedMainPost: [],
        checkedSubPost: [],
        mode: 'transfer',
        defaultProps: {
          label: 'postName',
          key: 'id'
        },
        filterName: '',
        filterJobName: '',
        leafOnly: true,
        userId: '',
        defaultMainkedKeys: [],
        defaultSubKeys: [],
        renderFunc: (h, option) => {
          // let self = this;
          // let data = option.data;
          // return (<span class="role-trans">{option.data.roleName} {data.isRight === true ?
          //   <el-button size="mini" type="text" on-click={() => self.relieve(option.data)}
          //               style="float:right;width:20px;"><i class="soc icontime1"
          //                                                 style="font-size:20px;color:#8696B5;margin-right: 5px"></i>
          //   </el-button> : ''}</span>);
        }
      }
    },
    computed: {
      // defaultMainkedKeys() {
      //   return this.checkedMainPost.map((v) => v?.postId ?? v.id)
      // },
      // defaultSubKeys() {
      //   return this.postList.map((v) => v?.postId ?? v.id)
      // }
    },
    watch: {
      userInfo: {
        handler(val) {
          this.handleOpen(val)
        },
        immediate: true,
        deep: true
      }
    },
    mounted() {
      this.loadPostTree()
    },
    methods: {
      async handleOpen(info) {
        this.isVisible = true
        await this.loadPostTree()
        this.checkedMainPost = clone(info.mainPost ? [info.mainPost] : [])
        this.checkedSubPost = clone(info.deputyPosts || [])
        this.$forceUpdate()
        this.userId = info.id
      },
      async loadPostTree() {
        const { data, code, msg } = await apiPostTree()
        if (code === EnumApiCode.Success) {
          const result = data
          // result[0].parentId = 0
          this.subPostOptions = cloneDeep(result)
          this.mainPostOptions = cloneDeep(result)
        } else {
          this.$message.error(msg)
        }
      },
      // 查询部门岗位树
      queryAllPost() {},
      handleClick(tab, event) {},
      // 查询岗位
      searchPost(type) {
        let resul = ''
        if (type === 'main') {
          resul = this.filterName.replace(/(^\s*)|(\s*$)/g, '')
        } else {
          resul = this.filterJobName.replace(/(^\s*)|(\s*$)/g, '')
        }
        this.queryAllPost()
      },
      //  穿梭 添加
      transferMainAdd(fromData, toData, obj) {
        this.mainPostOptions = fromData
        this.checkedMainPost = toData
      },
      remove(fromData, toData, obj) {
        this.mainPostOptions = fromData
        this.checkedMainPost = toData
      },
      transferDeputyAdd(fromData, toData, obj) {
        this.subPostOptions = fromData
        this.checkedSubPost = toData
      },
      transferDeputyRemove(fromData, toData, obj) {
        this.subPostOptions = fromData
        this.checkedSubPost = toData
      },
      leftCheckChange(nodeObj, treeObj, checkAll) {
        if (this.checkedMainPost.length || treeObj.checkedKeys.length !== 1) {
          this.$refs.mainPost.clearChecked()
          this.$message.success('主岗有且只能有一个！')
        }
      },
      handleClose() {
        this.loading = false
        this.isVisible = false
        this.checkedMainPost = []
        this.checkedSubPost = []
        this.defaultMainkedKeys = []
        this.defaultSubKeys = []
      },
      handleSubmit() {
        if (!this.checkedMainPost.length) {
          this.$message.error('请选择主岗')
          return
        }
        this.loading = true
        const list = [
          ...this.checkedMainPost.map((v) => {
            return { postId: v.id, userId: this.userId, postType: 1, deptId: v.deptId, orgId: v.orgId }
          }),
          ...this.checkedSubPost.map((v) => {
            return { postId: v.id, userId: this.userId, postType: 0, deptId: v.deptId, orgId: v.orgId }
          })
        ]
        apiPostUserPost(list).then(
          ({ code, msg }) => {
            if (code === EnumApiCode.Success) {
              this.$message.success(this.$t('system.user.successTips'))
              this.$emit('handleSuccess')
              this.handleClose()
            } else {
              this.$message.error(msg)
            }
          },
          () => {
            this.loading = false
          }
        )
      }
    }
  }
</script>

<style lang="scss" scoped>
  .title {
    font-size: 16px;
    line-height: 25px;
    box-sizing: border-box;
    width: 80px;
    margin-bottom: 16px;
    padding: 0 12px 0 0;
    text-align: right;
    color: #606266;
  }

  .flex-row {
    display: flex;
  }

  .justify-between {
    justify-content: space-between;
  }

  .required-icon {
    margin-right: 4px;
    color: #f56c6c;
  }

  .input-with-search {
    width: 300px;
  }
</style>
<style lang="scss">
  .input-with-search {
    .el-input-group__append {
      line-height: 30px !important;
      height: 30px;
    }

    .el-button--medium {
      padding: 6px 20px;
    }
  }
</style>
